<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单元名称" prop="unitName">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入单元名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:unit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:unit:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="unitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属课程名称" align="center" prop="courseName" />
      <el-table-column label="单元名称" align="center" prop="unitName" />
      <el-table-column label="单元说明" align="center" prop="remark" />

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:unit:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:unit:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleAllocateWord(scope.row)"
            v-hasPermi="['system:unit:edit']"
          >配置单词</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteAllWords(scope.row)"
            v-hasPermi="['system:unit:edit']"
          >删除全部单词</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改单元对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所在课程" prop="courseId">
          <treeselect v-model="form.courseId" :options="courseOptions" :disable-branch-nodes="true" :multiple="false" :show-count="true" placeholder="请选择所属单元" />
        </el-form-item>
        <el-form-item label="单元名称" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入单元名称" />
        </el-form-item>
        <el-form-item label="单元说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配单词对话框 -->
    <el-dialog :title="title" :visible.sync="openAllocateWord" width="800px" append-to-body>
      <el-transfer v-model="wordIds" :data="wordList" :titles="['待分配', '已分配']" :props="{key: 'wordId', label: 'wordName'}" @change="handleUserSelect"></el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddUserToUnit">确 定</el-button>
        <el-button @click="closeAllocateWord">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCourse} from "@/api/system/course";
import { listUnit, getUnit, delUnit, addUnit, updateUnit, courseTreeSelect } from "@/api/system/unit";
import { listAllWord, listSelectedWord, addBatchUnitWord, deleteUnitWordByUnitId } from "@/api/system/word";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "Unit",
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单元表格数据
      unitList: null,
      // 课程数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示单词分配弹出层
      openAllocateWord: false,
      // 学员列表数据
      wordList: [],
      // 已选择的学员列表
      wordIds: [],
      // 当前选中的单元ID
      currentUnitId: null,
      // 所有课程树选项
      courseOptions: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unitName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        unitName: [
          { required: true, message: "单元名称不能为空", trigger: "blur" }
        ]
      },
      // 导入参数
      upload: {
        open: false,
        title: "",
        isUploading: false,
        url: process.env.VUE_APP_BASE_API + "system/word/importData",
        courseType: undefined,
        headers: { Authorization: "Bearer " + getToken() },
        rules: {
          courseType: [
          ]
        }
      }
    };
  },
  created() {
    this.getList();
    this.getAllWordList();
    this.initCourseTree();
  },
  methods: {
    /** 查询单元列表 */
    getList() {
      this.loading = true;
      listUnit(this.queryParams).then(response => {
        this.unitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询课程下拉树结构 */
    initCourseTree() {
      courseTreeSelect().then(response => {
        this.courseOptions = response.data;
        // this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
        console.log(this.unitOptions);
      });
    },
    /** 提交按钮操作 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.unitId != undefined) {
            updateUnit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUnit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const unitIds = row.unitId || this.ids;
      this.$modal.confirm('是否确认删除单元编号为"' + unitIds + '"的数据项？').then(function() {
        return delUnit(unitIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 取消按钮操作 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        UnitId: undefined,
        unitName: undefined,
        unitDesc: undefined
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加单元";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const unitId = row.unitId || this.ids;
      getUnit(unitId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改单元";
      });
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.unitId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.handleQuery();
    },
    /** 分配单词操作 */
    handleAllocateWord(row) {
      this.title = "单元：" + row.unitName;
      this.openAllocateWord = true;
      this.currentUnitId = row.unitId;
      this.getSelectedWordList(row.unitId);
    },
    /** 获取所有单词列表 */
    getAllWordList(unitId) {
      listAllWord({unitId: unitId}).then(response => {
        this.wordList = response.rows;
      });
    },
    /** 获取已分配学员列表 */
    getSelectedWordList(unitId) {
      listSelectedWord(unitId).then(response => {
        this.wordIds = response.rows.map(item => item.wordId);
        // this.userIds = [4, 5];
        console.log('this.wordIds---', this.wordIds);
      });
    },
    /** 学员选择事件 */
    handleUserSelect(value) {
      this.wordIds = value;
      console.log('handleUserSelect---', value);
    },
    /** 提交学员分配 */
    submitAddUserToUnit() {
      addBatchUnitWord(this.currentUnitId, this.wordIds).then(response => {
        this.$modal.msgSuccess("分配成功");
        this.openAllocateWord = false;
      });
    },
    /** 关闭分配对话框 */
    closeAllocateWord() {
      this.openAllocateWord = false;
      this.currentUnitId = null;
      this.wordIds = [];
    },
    /** 删除全部单词 */
    handleDeleteAllWords(row) {
      const unitId = row.unitId;
      this.$modal.confirm('是否确认删除该单元下的全部单词？').then(function() {
        return deleteUnitWordByUnitId({
          unitId: unitId
        });
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
}

</script>
